package leetcode100;

// TODO 递归+回溯+剪枝 [经典] 【-】 全排列
// TODO https://leetcode.cn/problems/permutations/solution/chou-xiang-cheng-jue-ce-shu-yi-ge-pai-lie-jiu-xian/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class lc100_0046 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    // 通过 map 记录当前数字是否已出现过
    Map<Integer, Integer> visited = new HashMap<>();

    public List<List<Integer>> permute(int[] nums) {
        dfs(nums, 0);
        return res;
    }

    public void dfs(int[] nums, int length) {
        // 递归结束控制器
        if (length == nums.length) {
            res.add(new ArrayList<>(path));
        }
        // 递归
        for (int i=0; i<nums.length; i++) {
            if (visited.containsKey(nums[i])) {
                continue;
            }
            path.add(nums[i]);
            visited.put(nums[i], 1);
            dfs(nums, length+1);
            // 回溯
            path.remove(path.size() - 1);
            visited.remove(nums[i]);
        }
    }
    
}